<?php
/**
 * Created by PhpStorm.
 * User: anyuzhe
 * Date: 2017/3/26
 * Time: 15:06
 */

namespace App\Repositories;

use InfyOm\Generator\Common\BaseRepository;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class PicturesRepository extends BaseRepository {

    public function model() {
        return 'App\Models\Picture';
    }

    public function uploadByHash($file,$directory,$user_id,$data)
    {
        if($has = $this->checkExist($file)){
            return $has;
        }
//        dd($file->getClientOriginalName());
        $path = $file->hashName($directory);
        $ok = Storage::disk('local')->put('public/'.$path, file_get_contents($file->path()));
//        $ok = Storage::disk('oss')->put($path, file_get_contents($file->path()));
        if($ok){
            $url = config('app.pic_oss_url_domain').$path;
//            $url = config('app.pic_oss_url_domain').$path;
            $picture = $this->saveToDB($path,$url,$file,$user_id,$data);
            return $picture;
        }else{
            return false;
        }
    }

    public function uploadOne($file,$path)
    {
        $ok = Storage::disk('oss')->put($path, file_get_contents($file));
        if($ok){
            $url = config('app.pic_oss_url_domain').$path;
            return $url;
        }else{
            return false;
        }
    }


    public function saveToDB($path,$uri,$file,$user_id,$data)
    {
        return $this->create([
            'path'=>$path,
            'url'=>$uri,
            'file_name'=>$file->getClientOriginalName(),
            'size'=>$file->getSize(),
            'md5'=>md5(file_get_contents($file->path())),
            'user_id'=>$user_id,
            'width'=>isset($data['width'])?$data['width']:0,
            'height'=>isset($data['height'])?$data['height']:0,
        ]);
    }

    public function checkExist($file)
    {
        return $this->findBy('md5',md5(file_get_contents($file->path())));
    }

    public function getModels($ids)
    {
        $data = [];
        if($ids){
            $ids = $this->checkIds($ids);
            foreach ($ids as $id) {
                $_data = $this->find($id);
                if($_data)
                    $data[] = $_data;
            }
            return $data;
        }else{
            return $data;
        }
    }

    public function checkIds($ids)
    {
        if(strpos($ids,',')){
            return explode(',',$ids);
        }else{
            $data = [$ids];
            return $data;
        }
    }

    //flow
    public function getIds($picture_ids,$picture_id)
    {
        return ['ids'=>$ids = $picture_ids?$picture_ids:$picture_id];
    }

    public function getModelByIds($ids,$cover_url)
    {
        if(isset($ids) && $ids){
            $pics = $this->getModels($ids);
            $cover_url = isset($pics[0])?$pics[0]->url:$cover_url;
            return ['pics'=>$pics,'cover_url'=>$cover_url];
        }
        return ['pics'=>null];
    }
}
